<template>
  <el-container class="custom-container">
    <CustomModel
      :type="showModelType"
      :options="modelOptions"
      v-if="showModelType != ''"
      @closeModel="closeModel"
      @loginSuccess="loginSuccess"
      @uploadImageToChat="uploadImageToChat" />
    <el-aside class="custom-aside">
      <img
        src="../assets/image/fsrb-mengyi-icon-with-text.png"
        class="aside-logo" />
      <div class="aside-new-dialog-button" @click="newDialog">
        <img src="../assets/image/add.png" class="create-icon" />
        <span class="create-text">新建对话</span>
      </div>
      <div class="menu-container">
        <div
          v-for="(item, index) in menuList"
          :key="index"
          class="menu-item-wrapper">
          <div
            :class="
              activeMenuIndex == item.menuId ? 'menu-item active' : 'menu-item'
            "
            @click="handelUnfoldMenu(item)">
            <img :src="item.icon" class="menu-item-icon" />
            <span class="menu-item-text">{{ item.title }}</span>
          </div>
          <div class="submenu-wrapper">
            <div
              v-if="!history[item.menuId] || history[item.menuId].length == 0"
              :class="`submenu-empty ${
                activeMenuIndex == item.menuId ? '' : 'hide'
              }`">
              <img
                src="../assets/image/no-history.png"
                :class="`empty-img ${
                  activeMenuIndex == item.menuId ? '' : 'hide'
                }`" />
              <div
                :class="`empty-text ${
                  activeMenuIndex == item.menuId ? '' : 'hide'
                }`">
                暂无记录
              </div>
            </div>
            <div v-else class="submenu-item-wrapper">
              <div
                :class="
                  activeMenuIndex == item.menuId
                    ? 'submenu-title'
                    : 'submenu-title hide'
                ">
                历史对话
              </div>
              <div
                v-for="(subItem, subIndex) in history[item.menuId]"
                :key="subIndex"
                :class="`submenu-item ${
                  activeMenuIndex == item.menuId ? ' ' : 'hide '
                }${activeSubmenuIndex == subItem.id ? 'active' : ''}`"
                @click="handelClickSubmenu(subItem)">
                <img
                  src="../assets/image/history-dia.png"
                  class="submenu-item-img" />
                <div class="submenu-item-text">{{ subItem.dialogueName }}</div>
                <img
                  class="submenu-item-icon"
                  v-if="subItem.accessType == 1"
                  src="../assets/image/pc-icon.png" />
                <img
                  class="submenu-item-icon"
                  v-else
                  src="../assets/image/mp-icon.png" />
                <img
                  :data-id="subItem.id"
                  class="submenu-item-icon delete"
                  src="../assets/image/delete-dialog.png"
                  @click="deleteDialog" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-aside>
    <el-main class="custom-main">
      <el-header class="custom-header">
        <div class="bread-crumb">
          <img
            src="../assets/image/bread-crumb-icon.png"
            class="bread-crumb-icon" />
          <span class="bread-crumb-text">{{ currentMenuName }}</span>
        </div>
        <div class="header-login" v-if="!login">
          <div class="login-button" @click="goLogin">登录 / 注册</div>
        </div>
        <div class="header-login" v-else>
          <el-dropdown @command="handelDropdown">
            <img
              class="user-avatar"
              src="http://chunfengai.top:29001/download/avatar-gender.png" />
            <el-dropdown-menu slot="dropdown">
              <span class="user-phone-number">{{
                userInfo.answeUserName
              }}</span>
              <el-dropdown-item command="user"
                ><i class="el-icon-edit"></i>编辑资料</el-dropdown-item
              >
              <el-dropdown-item command="logout"
                ><i class="el-icon-switch-button"></i>退出登录</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </el-header>
      <ChatContainer
        class="custom-chat-container"
        :userId="userId"
        :answeUserId="answeUserId"
        :key="chatKey"
        :appMenuId="activeMenuIndex"
        :history="dialogId > 0 ? dialogId : 0"
        :imageList="imageNameList"
        :imageUrlList="imageUrlList"
        @newDialogCreated="handelNewDialog"
        @goLogin="goLogin"
        @startDialog="startDialog"
        @showUploadModel="showUploadModel"
        @showAgeement="showModel('agreement')"
        @currentMenuChange="handleCurrentMenuId" />
    </el-main>
  </el-container>
</template>

<script>
  import { deleteCookie } from '../utils/setCookie'
  import request from '../utils/request.js'
  import ChatContainer from './components/chatContainer.vue'
  import CustomModel from '../components/customModel.vue'
  // import LoginModel from './components/loginModel.vue'
  export default {
    name: 'CustomPage',
    props: {},
    components: { ChatContainer, CustomModel },
    data() {
      return {
        userId: localStorage.getItem('userId'),
        // token: localStorage.getItem('token'),
        answeUserId: '',
        menuList: [],
        showLoginModel: false,
        login: false,
        userInfo: {},
        activeMenuIndex: -1,
        activeSubmenuIndex: -1,
        history: {},
        showModelType: '',
        dialogId: -1,
        chatKey: 0,
        modelOptions: {},
        imageNameList: [],
        imageUrlList: [],
        currentMenuName: '',
      }
    },
    computed: {},
    watch: {
      activeSubmenuIndex(n, o) {
        this.dialogId = n
        console.log('submenu index :>> ')
        // this.requireHistory(this.activeMenuIndex)
      },
      activeMenuIndex(n, v) {
        if (n != -1) {
          this.requireHistory(n)
        }
      },
      dialogues() {
        console.log('dia change :>> ')
      },
    },
    created() {
      this.requireMenuList()
      new Promise((resolve, reject) => {
        this.userId ? resolve() : reject()
      })
        .then((res) => {
          this.login = true
          this.requireUserInfo()
        })
        .catch((err) => {
          console.log('show login in custom :>> ')
          this.goLogin()
        })

      //
    },
    mounted() {},
    methods: {
      handleCurrentMenuId(e) {
        console.log('handleCurrentMenuId :>> ', e)
        let t
        this.menuList.forEach((i) => {
          if (i.menuId == e) {
            t = i.title
          }
        })
        this.currentMenuName = t ? t : ''
      },
      deleteDialog(e) {
        e.stopPropagation()
        let id = e.target.dataset.id
        this.$confirm('确认删除对话？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            console.log('deleteDialog :>> ', id)
            this.requireDelete(id)
          })
          .catch(() => {})
      },
      uploadImageToChat(list1, list2) {
        this.imageNameList = list1
        this.imageUrlList = list2
      },
      showUploadModel() {
        this.showModelType = 'upload'
        this.modelOptions = {
          answeUserId: this.answeUserId,
          userId: this.userId,
        }
      },
      startDialog(item) {
        // this.newDialog()
        this.changeChatStatus()
      },
      loginSuccess() {
        // this.$forceUpdate()
      },
      handelNewDialog(e) {
        this.dialogId = e
      },
      handelDropdown(c) {
        if (c == 'user') {
          this.showModel('user')
        } else if (c == 'logout') {
          this.logout()
        }
      },
      handelUnfoldMenu(e) {
        if (e.menuId == this.activeMenuIndex) {
          this.activeMenuIndex = -1
        } else {
          this.activeMenuIndex = e.menuId
        }
        // if (!history[e.menuId]) {
        //   this.requireHistory(e.menuId)
        // }
      },
      handelClickSubmenu(e) {
        this.activeSubmenuIndex = e.id
        this.dialogId = e.id
        this.handleCurrentMenuId(this.activeMenuIndex)
        this.changeChatStatus()
      },
      newDialog() {
        this.activeSubmenuIndex = -1
        this.activeMenuIndex = -1
        this.dialogId = -1
        this.currentMenuName = ''
        this.changeChatStatus()
      },
      startNewDialog(id) {
        this.dialogId = id
      },
      changeChatStatus() {
        this.chatKey += 1
      },
      goLogin() {
        this.showModelType = 'login'
        this.login = false
        // this.$message('please login')
        // this.$showLogin()
      },
      logout() {
        this.$confirm('是否退出登录?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.$message({
              type: 'success',
              message: '已退出登录',
            })
            deleteCookie('userId')
            localStorage.clear()
            location.reload()
            this.goLogin()
          })
          .catch(() => {})
      },
      closeModel(e) {
        console.log('close model page :>> ', e)
        this.showModelType = ''
        this.modelOptions = {}
        if (e) {
          location.reload()
        }
      },
      refreshPage() {},
      showModel(type) {
        console.log('show model :>> ', type)
        this.showModelType = type
      },
      requireMenuList() {
        this.req({ method: 'GET', url: '/applet/menu/list' }).then((res) => {
          this.menuList = res.data.data
          localStorage.setItem('menuList', JSON.stringify(res.data.data))
        })
      },
      requireUserInfo() {
        if (!this.userId) {
          return
        }
        this.req({
          method: 'POST',
          url: `/applet/answer/user/get/default/${this.userId}`,
        }).then((res) => {
          this.userInfo = res.data.data.tbAnsweUser
          this.answeUserId = res.data.data.tbAnsweUser.answeUserId
          localStorage.setItem(
            'userInfo',
            JSON.stringify(res.data.data.tbAnsweUser)
          )
        })
      },
      requireCreateNewDig() {
        let data = {}
        this.req({
          method: 'POST',
          url: '/applet/answer/user/list',
          data,
        })
      },
      requireHistory(appMenuId) {
        let data = {
          userId: this.userInfo.userId,
          answeUserId: this.userInfo.answeUserId,
          pageNum: 1,
          pageSize: 1000,
          appMenuId,
        }
        this.req({
          method: 'POST',
          url: '/applet/dialog/page/byappmenu',
          data,
        }).then((res) => {
          this.$set(this.history, appMenuId, res.data.data.rows)
          // this.history[appMenuId] =
        })
      },
      requireDelete(id) {
        this.req({
          method: 'POST',
          url: '/applet/dialog/deleteDig',
          data: { id: Number(id) },
        }).then((res) => {
          this.$message({
            type: 'success',
            message: '删除对话成功',
          })
          this.requireHistory(this.activeMenuIndex)
        })
      },
      req(params) {
        return new Promise((resolve, reject) => {
          request(params)
            .then((res) => {
              if (res.data.code == 200) {
                resolve(res)
              } else if (res.data.code == 401) {
                this.goLogin()
                // this.$message({
                //   message: res.data.msg,
                // })
              } else {
                console.log('custom page req error :>> ', err)
              }
            })
            .catch((err) => {
              if (err == 401) {
                this.goLogin()
              }
              console.log('custom page error :>> ', err)
            })
        })
      },
    },
  }
</script>
<style scoped lang="less">
  * {
    box-sizing: border-box;
  }
  .custom-container {
    height: 100vh;
    display: flex;
    box-sizing: border-box;
  }
  .custom-aside {
    width: 300px;
    height: 100%;
    padding: 28px 16px;
    background: linear-gradient(180deg, #44878b 0%, #65b0b4 100%);
    border-radius: 0px 16px 16px 0px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
  }
  .aside-logo {
    width: 100%;
    height: auto;
    margin-bottom: 40px;
  }
  .aside-new-dialog-button {
    width: 100%;
    background: rgba(255, 255, 255, 0.15);
    border-radius: 6px 6px 6px 6px;
    border: 1px solid #ffffff;
    padding: 11px 0px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 500;
    color: #ffffff;
    cursor: pointer;
    .create-icon {
      height: 18px;
      width: 18px;
      margin-right: 8px;
    }
    .create-text {
      font-size: 16px;
      line-height: 19px;
    }
  }
  .menu-container {
    margin-top: 16px;
    width: 100%;
    display: flex;
    flex-direction: column;
    .menu-item-wrapper {
      width: 100%;
      height: fit-content;
      display: flex;
      flex-direction: column;
    }
    .menu-item {
      // height:44px;
      padding: 8px 16px;
      border-radius: 6px 6px 6px 6px;
      display: flex;
      align-items: center;
      opacity: 0.8;
      cursor: pointer;
      transition: all 0.2s;
      .menu-item-icon {
        margin-right: 8px;
        width: 30px;
        height: 30px;
      }
      .menu-item-text {
        font-size: 16px;
        font-weight: 500;
        color: #ffffff;
        line-height: 19px;
      }
      &.active {
        opacity: 1;
        background: rgba(255, 255, 255, 0.15);
      }
    }
    .menu-item:hover {
      opacity: 1;
    }
    .submenu-wrapper {
      display: flex;
      flex-direction: column;
      width: 100%;
      .submenu-empty {
        width: 100%;
        height: 120px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        opacity: 0.6;
        overflow: hidden;
        transition: all 0.2s;
        .empty-img {
          width: 90px;
          height: 68px;
          margin-bottom: 4px;
        }
        .empty-text {
          font-size: 12px;
          color: #fff;
          overflow: hidden;
        }
      }
      .submenu-item-wrapper {
        display: flex;
        flex-direction: column;
        width: 100%;
        margin-bottom: 4px;
      }
      .submenu-title {
        height: 28px;
        padding: 8px 0px 4px 16px;
        color: rgba(255, 255, 255, 0.6);
        font-size: 12px;
        overflow: hidden;
      }
      .submenu-item {
        height: 36px;
        padding: 8px 0px 8px 16px;
        display: flex;
        flex-direction: row;
        align-items: center;
        opacity: 0.8;
        border-radius: 4px 4px 4px 4px;
        transition: all 0.2s;
        cursor: pointer;
        overflow: hidden;
        .submenu-item-img {
          height: 18px;
          width: 18px;
          margin-right: 8px;
        }
        .submenu-item-text {
          font-size: 14px;
          color: #fff;
          width: 100%;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        .submenu-item-icon {
          height: 20px;
          width: 20px;
          opacity: 0;
          margin-right: 8px;
          cursor: default;
          transition: all 0.2s;
          &.type {
          }
          &.delete {
            z-index: 999;
            cursor: pointer;
          }
        }
        &.active {
          opacity: 1;
          background: rgba(255, 255, 255, 0.15);
        }
      }

      .hide {
        height: 0px;
        padding-top: 0px;
        padding-bottom: 0px;
      }
      .submenu-item:hover {
        opacity: 1;
        .submenu-item-icon {
          opacity: 1;
        }
      }
    }
  }
  .custom-main {
    width: calc(100% - 300px);
    background-color: #f4f8f9;
    padding: 0px;
  }
  .custom-header {
    width: 100%;
    height: 72px;
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .bread-crumb {
      display: flex;
      align-items: center;
      .bread-crumb-icon {
        height: 20px;
        width: 20px;
      }
      .bread-crumb-text {
        margin-left: 4px;
        color: #65b0b4;
        font-size: 14px;
      }
    }
    .header-login {
      // width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: end;
      // padding-right: 24px;
      .login-button {
        width: 120px;
        height: 40px;
        background: #65b0b4;
        border-radius: 4px 4px 4px 4px;
        text-align: center;
        color: #fff;
        line-height: 40px;
        cursor: pointer;
      }
      .user-avatar {
        width: 40px;
        height: 40px;
      }
    }
  }
  .user-phone-number {
    font-size: 14px;
    line-height: 36px;
    padding: 0px 20px;
    color: #65b0b4;
  }
  .custom-chat-container {
    // width: calc(100% - 300px);
    height: calc(100% - 72px);
    position: relative;
  }
</style>
